﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Runtime.InteropServices;
using System.ServiceModel;
using System.ServiceModel.Description;
using WindowServices.Interface;
using WindowServices.Server.Interface;

namespace WcfService
{
    [Description("插件服务管理服务.")]
    [DisplayName(@"插件服务远程管理服务")]
    [Guid("CF26C7AB-335C-4CF2-A06C-D93393D9097A")]
    [Serializable]
    public class WcfService : IService
    {
        ServiceHost _host;
        private string _hostUrl = "http://localhost:8089";
        private const string HostUrlKey = "HostUrl";
        public void Initialize(ServiceEntity serviceEntity)
        {
            LogServiceHelper.LogHelper.Logger.Info("正在初始化wcf服务。");
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[HostUrlKey]))
            {
                _hostUrl = ConfigurationManager.AppSettings[HostUrlKey];
            }

            LogServiceHelper.LogHelper.Logger.Info("初始化服务地址为：" + _hostUrl);
        }

        public void Start()
        {
            try
            {
                _host = new ServiceHost(typeof(WindowServices.Common.LocalServer), new Uri(_hostUrl));
                _host.AddServiceEndpoint(typeof(IServer), new BasicHttpBinding(), "");
                var behavior = _host.Description.Behaviors.Find<ServiceMetadataBehavior>();

                if (behavior == null)
                {
                    behavior = new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = new Uri(_hostUrl + "/Mex") };
                    _host.Description.Behaviors.Add(behavior);
                }
                else
                {
                    behavior.HttpGetEnabled = true;
                    behavior.HttpGetUrl = new Uri(_hostUrl);
                }


                _host.Open();
            }
            catch (Exception exception)
            {
LogServiceHelper.LogHelper.Logger.ErrorFormat("启动wcf服务出现异常:{0}",exception);
            }

        }

        public void Stop()
        {
            if (_host != null)
            {
                _host.Close();
            }
        }

        public void Pause()
        {
        }
    }
}
